/**
 * Created by jaliu on 2015/3/15.
 */
var Question = mongoose.model('question');
var Users = mongoose.model('user');
var async = require('async');
var appStartInfo = mongoose.model('system_appStartInfo');
var toolUtil = require('../../common/utils/toolUtil');
var Community = mongoose.model('community');
var communityApplications = mongoose.model('community_applications');
var moment = require('moment');
var json2csv = require('json2csv');
var fs = require('fs');
var ugcReply = mongoose.model('system_ugcReply');
var ugcIndex = mongoose.model('system_ugcIndex');
var neighbourActivity = mongoose.model('activity_neighbour');
var pushRecord = mongoose.model('system_pushRecords');
var operateMessage = mongoose.model('system_operateMessages');
var freshNews = mongoose.model('system_freshNews');

/**
 * 获取小区互助统计数据
 */

exports.getCommunityQuestionStatisticsService = function (opt, callback) {

    async.series([
        function (callbackInner) {

            Question.find({
                dateCreated: {
                    $gte: opt.startTime,
                    $lt: opt.endTime
                }
            }, 'replies createdBy').populate('createdBy', 'userType mobilePhone').populate('replies.repliedBy', 'userType mobilePhone').exec(function (err, result) {
                var tQuestions = new Array();
                var replies = new Array();
                var cQuestions = new Array();
                var cReplies = new Array();

                if (result != null) {
                    result.forEach(function (question) {
                        if (question.createdBy && question.createdBy.userType == 'talent') {
                            tQuestions.push(question)
                        }
                        if (question.replies != null) {
                            replies = replies.concat(question.replies);
                        }
                        if (question.createdBy && question.createdBy.mobilePhone == '66customerservice') {
                            cQuestions.push(question)
                        }
                    });
                    var users = uniqueQuestion(result);
                    var talents = uniqueQuestion(tQuestions);
                }

                var tReplies = new Array();

                replies.forEach(function (reply) {
                    if (reply.repliedBy && reply.repliedBy.userType == 'talent') {
                        tReplies.push(reply);
                    }
                    if (reply.repliedBy && reply.repliedBy.mobilePhone == '66customerservice') {
                        cReplies.push(reply);
                    }
                });

                var replyUsers = uniqueReply(replies);
                var replyTalents = uniqueReply(tReplies);

                var data = {
                    users: users == null ? 0 : users.length,            //发布人数
                    talents: talents == null ? 0 : talents.length,      //发布达人数
                    questions: result == null ? 0 : result.length,      //发布数
                    tQuestions: tQuestions.length,                      //达人发布数
                    cQuestions: cQuestions.length,                      //66发布数
                    replies: replies.length,                            //回复数
                    tReplies: tReplies.length,                          //达人回复数
                    replyUsers: replyUsers.length,                      //回复人数
                    replyTalents: replyTalents.length,                  //回复达人数
                    cReplies: cReplies.length                           //66回复数
                };
                callbackInner(err, data);
            })
        },
        function (callbackInner) {
            appStartInfo.count({
                dateCreated: {
                    $gte: opt.startTime,
                    $lt: opt.endTime
                }
            }, callbackInner)
        },
        function (callbackInner) {
            appStartInfo.find({
                dateCreated: {
                    $gte: opt.startTime,
                    $lt: opt.endTime
                }
            }).distinct('userId', function (err, results) {
                callbackInner(err, results == null ? 0 : results.length);
            })
        }
    ], callback)
};

exports.addCommunityService = function (input, callback) {

    var communityId;

    async.series([
        function (callbackInner) {
            var data = {
                communityName: input.name,
                communityAddress: input.address,
                city: input.city,
                households: Number(input.households),
                location: {
                    longitude: input.lng,
                    latitude: input.lat
                },
                communityLogo: input.communityLogo
            };
            if (input.unitSwitch != null) {
                data.unitSwitch = input.unitSwitch;
            }

            var temp = new Community(data);
            temp.save(function (err, result) {
                communityId = result._id;
                callbackInner();
            });
        },
        function (callbackInner) {
            toolUtil.getAndCacheHuanXinToken(function (err, token) {
                var args = {
                    data: {
                        "groupname": input.name + '群聊大厅', //群组名称, 此属性为必须的
                        "desc": input.name, //群组描述, 此属性为必须的
                        "public": true, //是否是公开群, 此属性为必须的
                        "maxusers": 20000, //群组成员最大数(包括群主), 值为数值类型,默认值200,此属性为可选的
                        "approval": false, //加入公开群是否需要批准, 没有这个属性的话默认是true（不需要群主批准，直接加入）, 此属性为可选的
                        "owner": '66customerService'//群组的管理员, 此属性为必须的
                    },
                    headers: {
                        "Content-Type": "application/json",
                        "Authorization": "Bearer " + token
                    }
                };
                restClient.post("https://a1.easemob.com/66xiaoqu/" + huanxinEnv + "/chatgroups", args, function (data, response) {
                    if (response.statusCode == 200 && data.data.groupid != null) {
                        Community.update({_id: communityId}, {chatGroupId: data.data.groupid}, callbackInner)
                    } else {
                        callbackInner()
                    }
                }).on('error', function (err) {
                    logger.error('create community chat group' + err.message);
                    callbackInner()
                });
            });
        }
    ], callback)

};

exports.searchCommunityByNameService = function (name, city, callback) {
    var cList = [];

    restClient.get('http://api.map.baidu.com/place/v2/search?&query=小区、' + name + '&region=' + city + '&scope=2&output=json&ak=AvRqTglpaKICTZ5iwyn06KZj&page_size=10&page_num=0', function (data, response) {
        var data = JSON.parse(data)
        if (response.statusCode == 200 && data.status == 0) {
            data.results.forEach(function (community, id) {
                var temp = {
                    id: id,
                    name: community.name,
                    address: community.address,
                    lat: community.location.lat,
                    lng: community.location.lng
                };
                cList.push(temp)
            })
        }

        callback(null, cList);

    }).on('error', function (err) {
        logger.error('get Community List by Coordinates went wrong on the request' + err.message);
        callback(null, cList);
    });
};

exports.changeCommunityStatusService = function (input, callback) {
    Community.update({_id: input.id}, {isValid: input.status}, callback);
};

/* db.community_applications列表 */
exports.getCommunityApplicationsService = function (input, callback) {
    //Community.update({_id: input.id}, {isValid: input.status}, callback);
    //specialTopics.find({}, '_id title imageURL dateCreated community').populate('community', '_id communityName').sort('-dateCreated').exec(callback);
    communityApplications.find().exec(callback);
};

var uniqueQuestion = function (array) {
    if (array == null || array.length == 0) {
        var re = [];
    } else {
        array.sort(function (a, b) {
            return a.createdBy - b.createdBy
        });
        var re = [array[0]];
        for (var i = 1; i < array.length; i++) {
            if (array[i].createdBy !== re[re.length - 1].createdBy) {
                re.push(array[i]);
            }
        }
    }
    return re;
};


var uniqueReply = function (array) {
    if (array == null || array.length == 0) {
        var re = [];
    } else {
        array.sort(function (a, b) {
            return a.repliedBy._id - b.repliedBy._id
        });
        var re = [array[0]];
        for (var i = 1; i < array.length; i++) {
            if (array[i].repliedBy._id !== re[re.length - 1].repliedBy._id) {
                re.push(array[i]);
            }
        }
    }
    return re;
};

/**
 * 创建user.csv
 */
exports.createUserCsvService = function (input, callback) {

    var startTime = new Date(input.startTime);
    startTime.setHours(startTime.getHours() - 8);

    var endTime = new Date(input.endTime);
    endTime.setHours(endTime.getHours() - 8);

    var opt = {
        dateCreated: {
            $gte: startTime,
            $lt: endTime
        }
    };

    if (input.community != null) {
        opt.community = input.community;
    }

    Users.find(opt, 'community _id mobilePhone nickName dateCreated apartmentDetail gender userPortrait birthDate wechatId authenticationStatus userType roomUnit roomNumber')
        .populate('userPortrait', 'value').populate('community', '_id communityName')
        .sort('dateCreated')
        .exec(function (err, results) {
            async.eachSeries(results, function (user, callback) {
                if (user.wechatId != null) {
                    if (user.wechatId.indexOf('o') == 0)
                        user._doc['loginWay'] = '微信';
                    else
                        user._doc['loginWay'] = 'QQ';
                } else {
                    user._doc['loginWay'] = '手机号';
                }
                user._doc.dateCreated = moment(user.dateCreated).format("YYYY-MM-DD HH:mm:ss");
                if (user.birthDate != null) {
                    user._doc.birthDate = moment(user.birthDate).format("YYYY-MM-DD");
                }
                if (user.userPortrait != null)
                    user._doc['portrait'] = user.userPortrait.value;

                if (user.userType == 'talent') {
                    user._doc['isTalent'] = '是'
                } else {
                    user._doc['isTalent'] = '不是'
                }

                if (user.authenticationStatus) {
                    user._doc['status'] = '是'
                } else {
                    user._doc['status'] = '不是'
                }

                if (user.community != null) {
                    user._doc['communityName'] = user.community.communityName;
                }

                async.series([
                    function (callbackInner) {
                        Question.count({
                            'createdBy': user._id,
                            isValid: true
                        }, function (err, questionCount) {
                            user._doc['questionCount'] = questionCount;
                            callbackInner(err, null);
                        })
                    },
                    function (callbackInner) {
                        Question.find({
                            'replies.repliedBy': user._id,
                            isValid: true
                        }, function (err, questions) {
                            var replyCount = 0;
                            var adoptCount = 0;
                            var userId = user._id + '';
                            questions.forEach(function (question) {
                                if (question.replies != null) {
                                    question.replies.forEach(function (reply) {
                                        if (reply.repliedBy == userId) {
                                            replyCount += 1;
                                            if (reply.replyStatus == '已采纳') {
                                                adoptCount += 1;
                                            }
                                        }
                                    })
                                }
                            });
                            user._doc['replyCount'] = replyCount;
                            user._doc['adoptCount'] = adoptCount;
                            callbackInner(err, null);
                        })
                    },
                    function (callbackInner) {
                        scoreProxy.invoke('getScoreInfoByUid', [user._id + ''], function (err, result) {
                            if (err) {
                                user._doc['score'] = 0;
                                callbackInner();
                            } else {
                                var data = JSON.parse(decodeURIComponent(result));
                                if (data.status != 0) {
                                    logger.error('getUserScore----' + data.msg);
                                    user._doc['score'] = 0;
                                    callbackInner()
                                } else {
                                    user._doc['score'] = data.data.scoreInfo.currentValue;
                                    callbackInner();
                                }
                            }
                        });
                    }
                ], callback)
            }, function (err) {
                json2csv({
                    data: results,
                    fields: ['nickName', 'score', 'communityName', 'status', 'isTalent', 'loginWay', 'mobilePhone', 'dateCreated', 'apartmentDetail', 'gender', 'portrait', 'birthDate', 'questionCount', 'replyCount', 'adoptCount', 'roomUnit', 'roomNumber'],
                    fieldNames: ['昵称', '情值', '小区', 'V认证', '达人', '登录方式', '手机号', '注册时间', '住址', '性别', '肖像', '生日', '问题数', '回复数', '被认定为最佳次数', '单元', '房号']
                }, function (err, csv) {
                    if (err) console.log(err);
                    fs.writeFile('public/csv/user.csv', csv, function (err) {
                        if (err) throw err;
                        console.log('file saved');
                    });
                    callback(err, null);
                });
            });
        });
};

exports.createUgcCsvService = function (input, callback) {
    var startTime = new Date(input.startTime);
    startTime.setHours(startTime.getHours() - 8);

    var endTime = new Date(input.endTime);
    endTime.setHours(endTime.getHours() - 8);

    var opt = {dateCreated: {$gte: startTime, $lt: endTime}};

    if (input.community != null) {
        opt.community = input.community;
    }

    ugcIndex.find(opt).sort('-dateCreated')
        .exec(function (err, result) {
            var data = [];
            async.eachSeries(result, function (ugc, callbackInner) {
                if (ugc.category == 'neighbourActivity') {
                    neighbourActivity.findOne({_id: ugc.ugcId})
                        .populate('tag', 'value _id').populate('community', 'communityName')
                        .populate('replies.repliedBy', '_id nickName images')
                        .populate('createdBy', '_id nickName images userType authenticationStatus roomUnit showUnit')
                        .exec(function (err, activity) {
                            if (activity != null) {

                                var tag = '';
                                if (activity.tag != null) {
                                    activity.tag.forEach(function (t) {
                                        tag += t.value
                                    })
                                }


                                if (activity.replies != null && activity.replies.length > 0) {
                                    activity.replies.forEach(function (reply) {
                                        var temp = {};
                                        temp.community = activity.community.communityName;
                                        temp.desc = activity.desc;
                                        temp.tag = tag;
                                        temp.createdBy = activity.createdBy.nickName;
                                        temp.dateCreated = moment(activity.dateCreated).format("YYYY-MM-DD HH:mm:ss");
                                        temp.replyDesc = reply.replyDesc;
                                        temp.repliedBy = reply.repliedBy.nickName;
                                        temp.browserCount = activity.browserCount;
                                        temp.dateReplied = moment(reply.dateReplied).format("YYYY-MM-DD HH:mm:ss");

                                        data.push(temp);
                                     })
                                } else {
                                    var temp = {};
                                    temp.community = activity.community.communityName;
                                    temp.desc = activity.desc;
                                    temp.tag = tag;
                                    temp.createdBy = activity.createdBy.nickName;
                                    temp.dateCreated = moment(activity.dateCreated).format("YYYY-MM-DD HH:mm:ss");
                                    temp.browserCount = activity.browserCount;
                                    data.push(temp);
                                }
                            }
                            callbackInner(err);
                        })
                } else {
                    Question.findOne({_id: ugc.ugcId})
                        .populate('tag', 'category value _id')
                        .populate('replies.repliedBy', '_id nickName images userType authenticationStatus')
                        .populate('community', '_id communityName')
                        .populate('createdBy', '_id nickName images userType authenticationStatus roomUnit showUnit')
                        .exec(function (err, question) {
                            if (question != null) {

                                var tag = '';
                                if (question.tag != null) {
                                    question.tag.forEach(function (t) {
                                        tag += t.value
                                    })
                                }

                                if (question.replies != null && question.replies.length > 0) {
                                    question.replies.forEach(function (reply) {
                                        var temp = {};
                                        temp.community = question.community.communityName;
                                        temp.desc = question.desc;
                                        temp.tag = tag;
                                        temp.createdBy = question.createdBy.nickName;
                                        temp.dateCreated = moment(question.dateCreated).format("YYYY-MM-DD HH:mm:ss");
                                        temp.replyDesc = reply.replyDesc;
                                        temp.repliedBy = reply.repliedBy.nickName;
                                        temp.dateReplied = moment(reply.dateReplied).format("YYYY-MM-DD HH:mm:ss");
                                        temp.browserCount = question.browserCount;
                                        data.push(temp);
                                    })
                                } else {
                                    var temp = {};
                                    temp.community = question.community.communityName;
                                    temp.desc = question.desc;
                                    temp.tag = tag;
                                    temp.createdBy = question.createdBy.nickName;
                                    temp.dateCreated = moment(question.dateCreated).format("YYYY-MM-DD HH:mm:ss");
                                    temp.browserCount = question.browserCount;
                                    data.push(temp);
                                }
                            }
                            callbackInner(err);
                        })
                }
            }, function (err) {

                json2csv({
                    data: data,
                    fields: ['community', 'desc', 'tag', 'browserCount', 'createdBy', 'dateCreated', 'replyDesc', 'repliedBy', 'dateReplied'],
                    fieldNames: ['小区', '描述', '标签', '浏览量', '创建者', '创建时间', '回复内容', '回复者', '回复时间']
                }, function (err, csv) {
                    if (err) console.log(err);
                    fs.writeFile('public/csv/ugc.csv', csv, function (err) {
                        if (err) throw err;
                        console.log('file saved');
                    });
                    callback(err, null);
                });
            })
        })
};

exports.getOperatePushStatisticsService = function (callback) {
    var data = [];
    pushRecord.find().sort('-dateCreated').exec(function (err, results) {
        async.eachSeries(results, function (record, callbackInner) {
            operateMessage.find({message: record.message}, function (err, result) {

                var notifyCount = 0;
                var noticeCount = 0;

                result.forEach(function (temp) {
                    if (temp.clickSource == 'notify') {
                        notifyCount += 1;
                    } else if (temp.clickSource == 'notice') {
                        noticeCount += 1;
                    }
                });

                var temp = {
                    message: record.message,
                    dateCreated: record.dateCreated,
                    notifyCount: notifyCount,
                    noticeCount: noticeCount,
                    pushCount: result.length
                };

                data.push(temp);
                callbackInner();
            })
        }, function (err) {
            callback(err, data);
        });
    })
};

exports.addActivityToFreshNewsService = function (input, callback) {
    var temp = new freshNews();
    temp.openType = 7;
    temp.tag = freshName.activity.tagName;
    temp.newsId = input._id;
    temp.createdBy = input.createdBy._id;
    temp.title = input.desc;
    temp.bgColor = freshName.activity.bgColor;
    temp.community = input.community._id;
    temp.save(callback);
};